package com.yueqian.framework.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.yueqian.framework.exception.JwtAuthenticationEntryPoint;
import com.yueqian.framework.filter.JwtAuthenticationFilter;

import lombok.RequiredArgsConstructor;


@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

	private final JwtAuthenticationFilter jwtAuthenticationFilter;

	private final AuthenticationProvider authenticationProvider;

	private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
		httpSecurity
				// 过滤请求
				.authorizeRequests()
				// 接口放行
				.antMatchers(
						"/generateVerifyCode/**",
						"/user/**",
						"/doc.html",
						"/swagger-resources/configuration/ui",
						"/swagger*",
						"/swagger**/**",
						"/webjars/**",
						"/**.ico",
						"/**.css",
						"/**.js",
						"/**.png",
						"/**.gif",
						"/v3/**",
						"/**.ttf",
						"/actuator/**",
						"/static/**",
						"/resources/**").permitAll()
				// 除上面外的所有请求全部需要鉴权认证
				.anyRequest()
				.authenticated()
				.and()
				// CSRF禁用
				.csrf()
				.disable()
				// 禁用HTTP响应标头
				.headers().cacheControl().disable()
				.and()
				// 基于JWT令牌，无需Session
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				//拦截器
				.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
				//认证或者授权异常处理类
				.exceptionHandling(exception -> exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))
				//认证处理机制
				.authenticationProvider(authenticationProvider)
		;


		;
		return httpSecurity.build();
//		http.csrf(AbstractHttpConfigurer::disable)
//				.authorizeHttpRequests(request -> request
//														  .requestMatchers()
//														  .permitAll()
//														  .anyRequest().authenticated())
//				.sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS))
//				.authenticationProvider(authenticationProvider)
//				.exceptionHandling(exception ->
//										   exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))
//				.addFilterBefore(
//						jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
//		return http.build();
	}
}
